<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import easyapi from '../api';
import { Plus,CirclePlus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
    //定义绑定的数据
    const tableData=ref([]);
    //控制新增信息窗口是否显示
    const addWinVisible=ref(false);
     //控制编辑信息窗口是否显示
     const editWinVisible=ref(false);
    //新增数据绑定对象
    const addObject=ref({});
    //编辑数据绑定对象
    const editObject=ref({});
    //查询数据的文本
    const checkObj=ref({
      size:3,
      page:1
    });
    const total=ref(90);
    //记录修改数据的下标
    var editIndex=-1;

    //上传头像窗口控制
    const uploadimgWinVisible = ref(false);
    //上传头像绑定的数据
    const imageUrl = ref({});
    //挂载页面时查询数据
    onMounted(async function() {
        checkData();
    });
    const del=function(index,row){
        ElMessageBox.confirm(
    '确定删除该行信息吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async function(){
        //提交数据
        let result=await easyapi.del("/api/user",row.id);
        if(result.code==200){
          //刷新表格数据
        tableData.value.splice(index,1);
        //提示删除成功
        ElMessage({
        type: 'success',
        message: '删除成功',
      })
        }else{
          ElMessage({
        type: 'info',
        message: result.message,
      })
        }
        
      })
    }
    //显示窗口
    const openAddWin=()=>{
        addObject.value={};
        addWinVisible.value=true;
    }
    const closeAddWin=()=>{
        addWinVisible.value=false;
    }
    //保存新增数据 addObject
    const addSave = async function() {
    try {
        // 表单验证
        for (const key in addObject.value) {
            if (!addObject.value[key]) {
                ElMessage({
                    type: 'warning',
                    message: `${key} 不能为空`,
                });
                return; // 阻止继续执行
            }
        }

        // 发送请求
        const result = await easyapi.postJson("api/userjson", addObject.value);

        if (result && result.data) {
            tableData.value.unshift(result.data);

            // 表格数据变更
            ElMessage({
                type: 'success',
                message: '保存成功',
            });

            // 提示成功后关闭窗口
            closeAddWin();
        } else {
            // 处理无数据的情况
            ElMessage({
                type: 'error',
                message: '保存失败，请重试',
            });
        }
    } catch (error) {
        // 捕获并处理请求中的错误
        console.error('保存失败:', error);
        ElMessage({
            type: 'error',
            message: '保存失败，请确保新增数据是否完整且合规。',
        });
    }
}
    //点击编辑按钮执行的方法
    const edit=function(index,row){
        //记录修改数据的下标
        editIndex=index;
        //绑定要修改的数据
        editObject.value.id=row.id;
        editObject.value.username=row.username;
        editObject.value.userpass=row.userpass;
        //打开对话框
        editWinVisible.value=true;
    }
    //保存编辑数据
    const editSave=async function(){   
      // for (const key in editObject.value) {
      //       if (!editObject.value.status&&!editObject.value[key]) {
      //           ElMessage({
      //               type: 'warning',
      //               message: `${key} 不能为空`,
      //           });
      //           return; // 阻止继续执行
      //       }
      //   }    
        //发送请求
        let result=await easyapi.putJson("/api/userjson",editObject.value);
        //刷新表格
        checkData();
        tableData.value[editIndex]=result.data;
        //提示       
        ElMessage({
        type: 'success',
        message: '保存成功',
        });
        editWinVisible.value=false;
    }
    const checkData=async function(val){
      //点击分页按钮
      if(typeof val == 'number'){
        checkObj.value.page=val;
      }
        //查询数据
        let result=await easyapi.get("/api/userA",checkObj.value);
        //更新表格数据
        tableData.value=result.data.list;
        total.value=result.data.count;
    }

    const uploadimg=function(index,row){
      uploadimgWinVisible.value=true;
      //显示该用户已经上传的头像
      editIndex=index;
      console.log(editIndex+"------------");
      editObject.value={...row};
      console.log(editObject.value+"------------");
    }
    const handleAvatarSuccess=function(result,uploadFile){
      console.log(result+"++++++++++++++++");
      console.log(uploadFile+"================");
      imageUrl.value='/api'+result.data;
      console.log(result.data+"+++++++++++");
    }
    const beforeAvatarUpload=function(){}
    const saveimg=async function(){
      //将文件的地址和id发送到后台
      editObject.value.img=imageUrl.value;
      //console.log(editObject.value.img+"----------");
      let result=await easyapi.putForm("/api/userimg",editObject.value);
      console.log("------------------")
      console.log(tableData.value[editIndex]);
      tableData.value[editIndex]=result.data;
      uploadimgWinVisible.value=false;
    }
</script>


<template>
    <el-input v-model="checkObj.username" style="width: 240px; height: 40px;" placeholder="请填入查询用户名" />
    <el-button type="primary" @click="checkData">查询</el-button>
    <el-button type="success" @click="openAddWin">新增</el-button>
    <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
    >
    <!-- <el-table-column prop="id" label="ID"  /> -->
    <el-table-column prop="img" label="头像"  >
      <template #default="scope">
     <el-image style="width: 100px; height: 100px"
      :src="scope.row.img" :fit="fit" />
      </template>
    </el-table-column>
    <el-table-column prop="username" label="用户名"  />
    <el-table-column label="操作" >
        <template #default="scope">
          <el-button type="info" @click="uploadimg(scope.$index,scope.row)">
            上传头像</el-button>
            <el-button type="danger" @click="del(scope.$index,scope.row)">
            删除</el-button>
            <el-button type="warning" @click="edit(scope.$index,scope.row)">
                编辑</el-button>
        </template>
    </el-table-column>
    </el-table>
    <!-- current-page分页组件初始显示的页码  size每页的条数--> 
    <el-pagination 
    :page-size="checkObj.size"
    :current-page="checkObj.page"
    background layout="prev, pager, next" :total="total"  @current-change="checkData" />
    <el-dialog v-model="uploadimgWinVisible" title="上传头像" width="500">
      <el-upload
      class="avatar-uploader"
      action="/api/userimg"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><CirclePlus /></el-icon>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="uploadimgWinVisible = false">取消</el-button>
        <el-button type="primary" @click="saveimg">
          保存
        </el-button>
      </div>
    </template>
    </el-dialog>
    <!-- start新增信息的弹出框-->
    <el-dialog v-model="addWinVisible" title="新增信息" width="500">
        <el-form :model="addObject">
      <el-form-item label="用户名" :label-width="80">
        <el-input v-model="addObject.username" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="userpass" label="密码" :label-width="80">
        <el-input v-model="addObject.userpass" autocomplete="off" placeholder="新建添加若不填写默认为0"/>
      </el-form-item>
        </el-form>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="addWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- end新增信息的弹出框-->
    <!-- start编辑信息的弹出框-->
    <el-dialog v-model="editWinVisible" title="编辑用户信息" width="500">
      <el-form :model="editObject">
        <el-form-item label="用户名" :label-width="80">
        <el-input v-model="editObject.username" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="userpass" label="密码" :label-width="80">
        <el-input v-model="editObject.userpass" autocomplete="off" />
      </el-form-item>
        </el-form>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="editWinVisible = false">取消</el-button>
        <el-button type="primary" @click="editSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- end编辑信息的弹出框-->
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>